#!/bin/sh

# This script takes three arguments: the name of the reference
# (branch), the SHA-1 that reference pointed to before the push, and
# the SHA-1 the user is trying to push.
refname=$1
oldrev=$2
newrev=$3
repodir=`pwd`

# Redirect output to stderr.
exec 1>&2

# Ignore branches that are not version branches or the master.
case $refname in
    refs/heads/master)
        branch=${refname##refs/heads/}
        worktree=/tmp/$branch-update-$$
        ;;
    refs/heads/version/*)
        branch=${refname##refs/heads/}
        worktree=/tmp/`echo $branch | tr '/' '-'`-update-$$
        ;;
    *)
        exit 0
        ;;
esac

# Check out a temporary version of the tree and work there.
git clone -q -b $branch $repodir $worktree
cd $worktree

# Need to reset GIT_DIR since it assumes a bare repository and we have
# now switched to a working tree.
GIT_DIR=.git/

# We do not allow non-ASCII filenames.
files_with_non_ascii=`git diff --cached --name-only --diff-filter=A -z $oldrev | LC_ALL=C tr -d '[ -~]\0' | wc -c`

if [ $files_with_non_ascii -ne 0 ]; then
    echo "Error: Attempt to add a non-ASCII file name. This can cause problems"
    echo "if you want to work with people on other platforms."
    exit 1
fi

# If there are whitespace errors, print the offending file names and fail.
git diff-index --check --cached $oldrev -- || exit 1

# Find cpplint and run it on all source and header files
cpplint=`which cpplint cpplint.py | head -1`
if [ -z "$cpplint" ]; then
    echo "Command 'cpplint' or 'cpplint.py' not found in path"
    exit 1
fi

dirs='harness plugins shared examples'
find $dirs '(' -name '*.cc' -o -name '*.h' ')' \
    -exec $cpplint {} + >/tmp/pre-commit-$$.txt 2>&1
if [ $? -ne 0 ]; then
    grep -v '^Done\|^Total' /tmp/pre-commit-$$.txt
    rm /tmp/pre-commit-$$.txt
    exit 1
else
    rm /tmp/pre-commit-$$.txt
fi
